﻿using _1._8._2015_AuthExample.Data;
using _1._8._2015_AuthExample.Data.Models;
using _1._8._2015_AuthExample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _1._8._2015_AuthExample.Adapters
{
    public class AddressDataAdapter : IAddressAdapter
    {
        public List<AddressViewModel> GetAddresses(string userId = null)
        {
            List<AddressViewModel> addresses = null;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var q = db.Addresses.AsQueryable();

                if (userId != null)
                {
                    q = q.Where(a => a.UserId == userId);
                }

                addresses = q.Select(a => new AddressViewModel
                {
                    City = a.City,
                    State = a.State,
                    Street = a.Street,
                    Zip = a.Zip,
                    Name = a.User.FirstName + " " + a.User.LastName
                }).ToList();
            }

            return addresses;
        }

        public void CreateAddress(CreateAddressViewModel model)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                db.Addresses.Add(new Address
                {
                    City = model.City,
                    State = model.State,
                    Street = model.Street,
                    Zip = model.Zip,
                    UserId = model.SelectedUserId
                });

                db.SaveChanges();
            }
        }

        #region Look up methods

        public List<LookUpModel> HydrateUserLookUpModels()
        {
            List<LookUpModel> models = null;

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                models = db.Users.Select(u => new LookUpModel
                {
                    Display = u.FirstName + " " + u.LastName,
                    Value = u.Id
                }).ToList();
            }
            
            return models;
        }

        #endregion

        public bool UpdateAddress(UpdateAddressViewModel model)
        {
            return true;
        }

        public string CanThisWork()
        {
            return "can you call this from the interface?";
        }
    }
}